package com.mrjy.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.record.formula.functions.T;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;

import com.mrjy.common.entity.SolrEntity;
import com.mrjy.common.entity.VideoType;
import com.mrjy.common.solr.SolrServerClient;
import com.mrjy.video.bo.IVideoTypeBo;
import com.mrjy.video.dao.IVideoTypeDao;
/**
 * Solr缓存工具类
 * @author csshui
 *
 */
public class SolrUtil {
	
	private static SolrServerClient solrServerClient;
	private static IVideoTypeBo videoTypeBo;
	private static Logger logger = Logger.getLogger(SolrUtil.class);
	static{
		solrServerClient = (SolrServerClient) SpringContextHelper.getBean("solrServerClient");
		videoTypeBo = (IVideoTypeBo)SpringContextHelper.getBean("videoTypeBo");
	}
	/**
	 * 将SolrDocument 转成 Bean
	 * @param doc 
	 * @param clazz 
	 * @return
	 */
	public static Object SolrDocumnet2Bean(SolrDocument  doc , Class clazz){
		Object obj = null ;
		try {
			obj = clazz.newInstance() ;
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		}
		Field[] fields = clazz.getDeclaredFields() ;
		for(Field field : fields){
			Object val = doc.get(field.getName());
			try {
				if (val != null) {
					BeanUtils.setProperty(obj, field.getName(), val);
				}
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return obj ;
	}
	/**
	 * 将SolrDocumentList转换成BeanList
	 * @param records
	 * @param clazz bean 的泛型
	 * @return
	 */
	 
	public static Object SolrDocumentList2BeanList(SolrDocumentList records, Class clazz){
		List list = new ArrayList();
        for(SolrDocument record : records){
            list.add(SolrDocumnet2Bean(record,clazz));
        }
        return list;
	}
	
	public static String formatVideoTypes(Integer[] ids) {
		String result = "";
		if (ids != null && ids.length > 0) {
			for (Integer id : ids) {
				Map<String, List<VideoType>> map = (Map<String, List<VideoType>>) videoTypeBo.queryById(id);
				result += map.get("rows").get(0).getTypeName()+",";
			}
			result = result.substring(0, result.length()-1);
		}
		return result;
	}
	
	
}
